package com.kcht.rfid.rd30.secretary.dispatch.impl.operation;

import com.google.protobuf.InvalidProtocolBufferException;
import com.kcht.rfid.rd30.secretary.core.command.LockCommand;
import com.kcht.rfid.rd30.secretary.core.command.BasicReaderCommand;
import com.kcht.rfid.rd30.secretary.core.common.ReaderResponseStatus;
import com.kcht.rfid.rd30.secretary.core.response.LockResponse;
import com.kcht.rfid.rd30.secretary.dispatch.IReaderChannel;
import lombok.extern.slf4j.Slf4j;
import uhf_msg.Uhf;

import java.time.LocalDateTime;
import java.util.Observer;
import java.util.Set;

/**
 *
 * 锁操作
 * */
@Slf4j
public class Lock extends BaseOperation {
    public Lock(Observer observer) {
        super(observer);
    }

    @Override
    protected void handlerOperation(IReaderChannel channel, Uhf.uhf_response response, Integer antId, BasicReaderCommand command) {
        LockCommand lockCommand=(LockCommand)command;
        String[] resList = response.getEpcInventRes().toString().split(" ");
        String epc = resList[resList.length-1];
        epc=epc.substring(1,epc.length()-2);
        Set<String> allowedEpcS = lockCommand.getAllowedEpcS();
        if(allowedEpcS == null || allowedEpcS.contains(epc)){
//            log.info("开始锁标签--->ip:{},天线接口:{},epc:{}",channel.getIp(),antId,epc);
            LockResponse reply=new LockResponse();
            reply.setEpc(epc);
            reply.setLockBank(lockCommand.getLockBank());
            reply.setLockAction(lockCommand.getLockAction());
            reply.setIp(channel.getIp());
            reply.setAntId(antId);
            Uhf.uhf_request request =lockRequest(lockCommand);
            byte[] recv = channel.sendRecv(request.toByteArray());
            if (recv != null) {
                Uhf.uhf_response lockResponse = null;
                try {
                    lockResponse = Uhf.uhf_response.parseFrom(recv);
                } catch (InvalidProtocolBufferException e) {
                    throw new RuntimeException("protoc不正确");
                }
                int lockStatus = lockResponse.getStatus();
                if (lockStatus == 0) {
                    log.info("锁标签成功--->ip:{},天线接口:{},epc{},操作区域:{},锁类型:{}",channel.getIp(),antId,epc,lockCommand.getLockBank(),lockCommand.getLockAction());
                    reply.setDateTime(LocalDateTime.now());
                    reply.setStatus(ReaderResponseStatus.成功);
                } else if (lockStatus == 1) {
                    reply.setDateTime(LocalDateTime.now());
                    if (lockResponse.getEpcLockRes().getErrCode() == 524353) {
                        log.error("锁标签失败,密码错误--->ip:{},天线接口:{},epc:{},密码:{}",channel.getIp(),antId,epc,command.getPwd());
                        reply.setStatus(ReaderResponseStatus.密码错误);
                    }else if(lockResponse.getEpcLockRes().getErrCodeTag() == 4){
                        log.error("锁标签失败,已经有永久锁--->ip:{},天线接口:{},epc{},区域:{},返回状态:1",channel.getIp(),antId,epc,lockCommand.getLockBank());
                        reply.setStatus(ReaderResponseStatus.已有永久锁);
                    }else{
                        log.error("锁标签失败,其他错误--->ip:{},天线接口:{},epc{},返回状态:1",channel.getIp(),antId,epc);
                        reply.setStatus(ReaderResponseStatus.失败);
                    }
                }
            } else {
                log.info("锁标签失败,接收响应超时--->ip:{},天线接口:{},epc{}",channel.getIp(),antId,epc);;
                reply.setDateTime(LocalDateTime.now());
                reply.setStatus(ReaderResponseStatus.响应超时);
            }
            super.response(reply);
        }
    }


    private  Uhf.uhf_request lockRequest (LockCommand command) {
        Uhf.uhf_request request = Uhf.uhf_request.getDefaultInstance();
        Uhf.uhf_request.Builder builder = request.toBuilder()
                .setType(Uhf.uhf_request.HeadType.epcLock)
                .setIso6CLock(Uhf.uhf_request.EpcLockPara.newBuilder()
                        .addPayLoad(Uhf.uhf_request.EpcPayloadPara.newBuilder()
                                .setLockMask(Uhf.uhf_request.EpcLockMask.forNumber(command.getLockBank().ordinal()))
                                .setLockAction(Uhf.uhf_request.EpcLockAction.forNumber(command.getLockAction().ordinal()))
                                .build()));

        if(!"无".equals(command.getPwd())){
            builder.setEpcAccess(uhf_msg.Uhf.uhf_request.EpcAccessPara.newBuilder()
                    .setPwdH(command.getHighPwd())
                    .setPwdL(command.getLowPwd())
                    .build());
        }
        request =builder.build();
        return request;
    }
}
